const mongoose = require('mongoose')
const Movie = mongoose.model('Movie')
const rp = require('request-promise')
const Category = mongoose.model('Category')
const _ = require('lodash')

// index page
exports.findAll = async () => {
  const data = await Category
    .find({})
    .populate({
      path: 'movies',
      select: 'title poster',
      options: { limit: 8 }
    })

  return data
}

// search page
exports.searchByCategory = async (catId) => {
  const data = await Category
    .find({_id: catId})
    .populate({
      path: 'movies',
      select: 'title poster'
    })

  return data
}

exports.searchByName = async (q) => {
  const data = await Movie.find({title: new RegExp(q + '.*', 'i')})

  return data
}

exports.findHotMovies = async (hot, count) => {
  const data = await Movie
    .find({})
    .sort({'pv': hot})
    .limit(count)

  return data
}

exports.findMoviesByCate = async (cat) => {
  const data = await Category
    .findOne({name: cat})
    .populate({
      path: 'movies',
      select: 'title poster _id'
    })

  return data
}

exports.searchById = async (id) => {
  const data = await Movie.findOne({_id: id})

  return data
}

const updateMovies = async (movie) => {
  const options = {
    uri: 'https://api.douban.com/v2/movie/subject/' + movie.doubanId,
    json: true
  }
  const data = await rp(options)

  _.extend(movie, {
    country: data.countries[0],
    language: data.language,
    summary: data.summary
  })

  console.log(data)

  const genres = movie.genres

  if (genres && genres.length > 0) {
    let cateArray = []

    genres.forEach(genre => {
      cateArray.push(async () => {
        let cat = await Category.findOne({name: genre})

        if (cat) {
          cat.movies.push(movie._id)
          await cat.save()
        } else {
          cat = new Category({
            name: genre,
            movies: [movie._id]
          })

          cat = await cat.save()
          movie.category = cat._id
          await movie.save()
        }
      })
    })

    Promise.all(cateArray)
  } else {
    movie.save()
  }
}

exports.searchByDouban = async (q) => {
  const options = {
    uri: `https://api.douban.com/v2/movie/search?q=${encodeURIComponent(q)}`,
    json: true
  }
  const data = await rp(options)
  let subjects = []
  let movies = []

  if (data && data.subjects) {
    subjects = data.subjects
  }

  if (subjects.length > 0) {
    let queryArray = []

    subjects.forEach(item => {
      queryArray.push(async () => {
        let movie = await Movie.findOne({doubanId: item.id})

        if (movie) {
          movies.push(movie)
        } else {
          const directors = item.directors || []
          const director = directors[0] || {}

          movie = new Movie({
            director: director.name || '',
            title: item.title,
            doubanId: item.id,
            poster: item.images.large,
            year: item.year,
            genres: item.genres || []
          })

          movie = await movie.save()
          movies.push(movie)
        }
      })
    })

    await Promise.all(queryArray)

    movies.forEach(movie => {
      updateMovies(movie)
    })
  }

  return movies
}
